package com.ruoyi.common.security.utils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

/**
 * @program: RuoYi-Cloud-master
 * @ClassName MyMarkAnnotation
 * @description:
 * @author: 段阳
 * @create: 2024-05-25 15:01
 **/
public class MyMarkAnnotation {

    public static String markDetail1(Object obj) {
        //这里是对数据进行脱敏处理
        if (obj instanceof String) {
            return obj.toString();
        }
        if (obj instanceof List) {
            return obj.toString();
        }
        StringBuilder strs = new StringBuilder();
        Class aClass = obj.getClass();//获取反射
        Field[] fields = aClass.getDeclaredFields();
        strs.append("{");
        Arrays.stream(fields).forEach(field -> {//通过stream流处理属性集合
            field.setAccessible(true);//设置私有对象可见
            try {
                //这个处理中没有对数据类型判断，统一当作字符串处理
                MarkAnnotation annotation = field.getAnnotation(MarkAnnotation.class);//获取字段上面的注解
                if (annotation != null) {//添加注解的
                    String mark = annotation.mark();//获得注解中的属性
                    int start = annotation.start();
                    int end = annotation.end();
                    if (!"".equals(mark)) {
                        String s = (String) field.get(obj);
                        if (s!=null){
                        if (start != 0||end !=0) {
                            //通过注解的属性对数据处理
                            String replace = s.substring(0, annotation.start()) + mark + s.substring(s.length() - annotation.end());
                            String ss = "\"" + field.getName() + "\":\"" + replace + "\",";
                            strs.append(ss);
                        } else {
                            String ss = "\"" + field.getName() + "\":\"" + mark + "\",";
                            strs.append(ss);
                        }
                        }else {
                            String ss = "\"" + field.getName() + "\":\"" + field.get(obj) + "\",";
                            strs.append(ss);
                        }
                    }
                } else {//没有添加注解的
                    String ss = "\"" + field.getName() + "\":\"" + field.get(obj) + "\",";
                    strs.append(ss);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });
        strs.append("}");
        //这里替换了最后一个逗号（可以在循环里处理）
        return strs.toString().replace(",}", "}");
    }
}